<?php
/*
 * 阿里云发送短信
 */
namespace app\common\lib\sms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms implements  SmsBase {

    /*
     * @desc 发送短信验证码的方法
     * @param string $phone 手机号
     * @param int $code     验证码
     * @return mixed
     */
    public static function sendCode(string $phone, int $code){
        //判断手机号和验证码是否为空
        if (empty($phone) || empty($code)){
            return false;
        }
        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
            ->regionId(config('aliyun.region_id'))
            ->asDefaultClient();
        $templateParam = [
            'code'=>$code
        ];
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('aliyun.host'))
                ->options([
                    'query' => [
                        'RegionId' =>config('aliyun.region_id'),
                        'SignName' => config('aliyun.sign_name'),
                        'PhoneNumbers'  =>  $phone,
                        'TemplateCode'  =>  config('aliyun.template_code'),
                        'TemplateParam' =>  json_encode($templateParam),
                    ],
                ])->request();
            //print_r($result->toArray());
            $result = $result->toArray();
            Log::info('aliyun_success_'.$phone.'_result'.json_encode($result));
        } catch (ClientException $e) {
            Log::error('aliyun_error_'.$phone.'_result'.$e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            Log::error('aliyun_error_'.$phone.'_result'.$e->getErrorMessage());
            return false;
        }
        if(isset($result['Code']) && ($result['Code'] == 'OK')){
             return true;
        }
        return false;
    }
}
